﻿using System;
using System.Collections.Generic;
using System.IO;
using CSJ2K.Util.IO;

namespace CSJ2K.Jpc.Segments
{
    /// <summary>Packed packet headers, main header (PPM)</summary>
    /// <comment>
    /// Function: A collection of the packet headers from all tiles. 
    ///      NOTE – This is useful so multiple reads are not required to decode headers. 
    /// Usage: Main header. May be used in the main header for all tile-parts unless a PPT 
    ///      marker segment is used in the tile-part header.  The packet headers shall be in 
    ///      only one of three places within the codestream. If the PPM marker segment is 
    ///      present, all the packet headers shall be found in the main header. In this case, 
    ///      the PPT marker segment and packets distributed in the bit stream of the tile-
    ///      parts are disallowed. If there is no PPM marker segment then the packet headers 
    ///      can be distributed either in PPT marker segments or distributed in the codestream 
    ///      as defined in B.10. The packet headers shall not be in both a PPT marker segment 
    ///      and the codestream for the same tile. If the packet headers are in PPT marker 
    ///      segments, they shall appear in a tile-part header before the corresponding packet 
    ///      data appears (i.e., in the same tile-part header or one with a lower TPsot value). 
    ///      There may be multiple PPT marker segments in a tile-part header. 
    /// Length: Variable depending on the number of packets in each tile-part and the size of 
    ///      the packet headers.
    /// </comment>
    public class PPM : Segment
    {
        /// <summary>Index of this marker segment relative to all other PPM marker segments present in the current header.</summary>
        public byte Z;        
        public struct TilePartInfo
        {
            /// <summary>Number of bytes of I information for the ith tile-part in the order found in the codestream.</summary>
            public uint N { get { return (uint)I.Length; } }

            /// <summary>packet header for every packet in order in the tile-part.</summary>
            public byte[] I;
        }
        public TilePartInfo[] TilePart;

        public PPM(Stream source)
            : this(source, (Markers)StreamUtil.ReadBUInt16(source)) { }
        public PPM(Stream source, Markers marker)
            : base(source, marker, true)
        {
            if (marker != Markers.PPM) throw (new ApplicationException("Attempting to create segment of the wrong type."));

            // TODO: Deserialize MarkerSegment
            byte[] buffer = StreamUtil.ReadBytes(source, Length - 2);
        }
    }
}

